//
//  XMN_ReadDetailViewController.m
//  B段项目
//
//  Created by dllo on 15/11/4.
//  Copyright © 2015年 谢美娜. All rights reserved.
//

#import "XMN_ReadDetailViewController.h"
#import "XMN_ReadDetailModel.h"

@interface XMN_ReadDetailViewController ()<UIWebViewDelegate>
@property(nonatomic, strong)UIWebView *webView;
@property(nonatomic, strong)XMN_ProgressHUD *HUD;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, strong)CoreDataManager *manager;
@property(nonatomic, strong)NSArray *selectArray;
@property(nonatomic, strong)NSString *night;
@end

@implementation XMN_ReadDetailViewController

-(void)loadView{
    [super loadView];
    //初始化webView
    _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    [self.view addSubview:_webView];
    _webView.scalesPageToFit = YES;
    _webView.delegate = self;
    [_webView NightWithType:UIViewColorType2];
    [self getDataByURLString];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([_titleString isEqualToString:@"null"]) {
        self.title = @"内容详情";
    }else{
       self.title = _titleString;
    }
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"XMN_like"] style:UIBarButtonItemStylePlain target:self action:@selector(collentAction)];
    _manager = [CoreDataManager shareManager];
    NSFetchRequest *fetchrequest = [NSFetchRequest fetchRequestWithEntityName:@"XMN_ReadDetailModel"];
    //查找条件
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid = %@", _idString];
    [fetchrequest setPredicate:predicate];
    //开始查询
    _selectArray = [_manager.managedObjectContext executeFetchRequest:fetchrequest error:nil];
    if (_selectArray.count != 0) {
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:1 green:0.69 blue:0.66 alpha:1];
        _flag = 1;
    }else{
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        _flag = 0;
    }

    // Do any additional setup after loading the view.
 
#pragma mark - 夜间模式
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"nightModel"]) {
        _night = @"1";
    }else{
        _night = @"0";
    }
    
    //注册消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNight:) name:@"WebNight" object:nil];
}

-(void)changeNight:(NSNotification *)notification{
    _night = (NSString *)[notification object];
}

-(void)webViewDidStartLoad:(UIWebView *)webView{
    _HUD = [[XMN_ProgressHUD alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, Height)];
    _HUD.backgroundColor = [UIColor colorWithRed:0.89 green:0.89 blue:0.9 alpha:1];
    _HUD.XMN_label.text = @"Waiting...";
    [self.view addSubview:_HUD];
}

-(void)getDataByURLString{
    [HTTPMethod getDataByString:@"http://api2.pianke.me/article/info" BODYDic:[ChangeString changeStringToDictionary:[NSString stringWithFormat:@"contentid=%@&client=2&auth=W8A7Rym2z8m3lDC8hwH8XikTJxQMCqYOXe8zo6Wj0xcWP22NBKTh5Z7Pg", _idString]] WithDataBlock:^(id data) {
        NSString *HtmlString = [[data objectForKey:@"data"] objectForKey:@"html"];
        [_webView loadHTMLString:HtmlString baseURL:nil];
    }];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    if ([_night isEqualToString:@"1"]) {
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor= '#555555'"];
        //字体颜色
        [_webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
    }
    
    //------------------------------------------------------------
    //修改JS语言
    //定义JS字符串(JavaScript)
    NSString *script = [NSString stringWithFormat:@"var script = document.createElement('script');"
                        "script.type = 'text/javascript';"
                        "script.text = \"function ResizeImages() { "
                        "var myimg;"
                        "var maxwidth = %f;"//屏幕宽度
                        "for (i = 0; i < document.images.length; i++) {"
                        "myimg = document.images[i];"
                        "myimg.height = maxwidth / (myimg.width / myimg.height);"
                        "myimg.width = maxwidth;"
                        "}"
                        "}\";"
                        "document.getElementsByTagName('p')[0].appendChild(script);", ScreenWidth - 20 * FitWidth];
    //添加JS
    [webView stringByEvaluatingJavaScriptFromString:script];
    //添加调用JS执行的语句
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    //------------------------------------------------------------
    [_HUD removeFromSuperview];
}

#pragma mark - 收藏
-(void)collentAction{
    if (_flag == 0) {
        DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"收藏成功" contentText:_titleString leftButtonTitle:@"取消" rightButtonTitle:@"确定"];
        [alert show];
        alert.rightBlock = ^(){
            self.navigationItem.rightBarButtonItem.tintColor = [UIColor colorWithRed:1 green:0.69 blue:0.66 alpha:1];
            _flag = 1;
            XMN_ReadDetailModel *model = [NSEntityDescription insertNewObjectForEntityForName:@"XMN_ReadDetailModel" inManagedObjectContext:_manager.managedObjectContext];
            model.cid = _idString;
            model.title = _titleString;
            model.image = _imageString;
            model.content = _contentString;
            [_manager saveContext];
        };
        
    }else{
        DXAlertView *alert = [[DXAlertView alloc]initWithTitle:@"取消收藏?" contentText:_titleString leftButtonTitle:@"取消" rightButtonTitle:@"确定"];
        [alert show];
        alert.rightBlock = ^(){
            self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
            _flag = 0;
            NSFetchRequest *fetchrequest = [NSFetchRequest fetchRequestWithEntityName:@"XMN_ReadDetailModel"];
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"cid = %@", _idString];
            [fetchrequest setPredicate:predicate];
            NSArray *array = [_manager.managedObjectContext executeFetchRequest:fetchrequest error:nil];
            XMN_ReadDetailModel *model = [array lastObject];
            [_manager.managedObjectContext deleteObject:model];
            [_manager saveContext];
        };
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
